package com.cwt_taxi_xa.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.os.StatFs;

/**
 * @author zr
 * 文件操作
 */
public class FileOper {
	private static final String TAG = "FileOper";
	List<File> list = new ArrayList<File>();
	/**
	 * 复制单个文件
	 * @param oldPath String 原文件路径
	 * @param newPath String 复制后路径
	 * @return boolean
	 */
	public static Boolean copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			//检查文件路径是否存在
			File filePath = new File(newPath);
			if(!filePath.exists()){
				filePath.mkdirs();
			}
			if (oldfile.exists()) { //文件存在时
				InputStream inStream = new FileInputStream(oldPath); //读入原文件
				FileOutputStream fs = new FileOutputStream(newPath+oldfile.getName().toString());
				byte[] buffer = new byte[1444];
				int length;
				while ( (byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; //字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				fs.flush();
				fs.close();
				inStream.close();
				return true;
			}
			return false;
		}
		catch (Exception e) {
			e.printStackTrace();
			return false;

		}

	}

	/**
	 * 获取文件/文件夹的大小
	 * @param size
	 * @return
	 */
	public static String getFileSize(long size){
		String len = "";
		if(size == 0){
			len = "0.00 KB";
		}else if(size < 1024){
			len = DecimalUtil.priceFormat(size)+" B";
		}else if(size < 1024 * 1024){
			BigDecimal decimal = new BigDecimal(size);
			decimal = decimal.divide(new BigDecimal(1024));
			len = DecimalUtil.priceFormat(decimal.doubleValue()) + " KB";
		}else if(size < 1024 * 1024 * 1024){
			BigDecimal decimal = new BigDecimal(size);
			decimal = decimal.divide(new BigDecimal(1024).multiply(new BigDecimal(1024)));
			len = DecimalUtil.priceFormat(decimal.doubleValue()) + " MB";
		}else {
			len = "缓存文件很大";
		}
		return len.replaceAll(".00", "");
	}

	/**
	 * 获取指定文件大小
	 * @param f
	 * @return
	 * @throws Exception
	 */
	public static long getFileSize(File file){
		long size = 0;
		try {
			if (file.exists()){
				FileInputStream fis = null;
				fis = new FileInputStream(file);
				size = fis.available();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return size;
	}

	public static int totalLen = 0;

	/**
	 * 复制整个文件夹内容
	 * @param oldPath String 原文件路径
	 * @param newPath String 复制后路径
	 * @return boolean
	 */
	public static boolean copyFolder(String oldPath, String newPath) {

		try {
			(new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
			File a=new File(oldPath);
			String[] file=a.list();
			File temp=null;
			for (int i = 0; i < file.length; i++) {
				if(oldPath.endsWith(File.separator)){
					temp=new File(oldPath+file[i]);
				}
				else{
					temp=new File(oldPath+File.separator+file[i]);
				}

				if(temp.isFile()){
					FileInputStream input = new FileInputStream(temp);
					FileOutputStream output = new FileOutputStream(newPath + "/" +
							(temp.getName()).toString());
					byte[] b = new byte[1024 * 5];
					int len;
					while ( (len = input.read(b)) != -1) {
						output.write(b, 0, len);
						totalLen = totalLen + len;
					}
					output.flush();
					output.close();
					input.close();
				}
				if(temp.isDirectory()){//如果是子文件夹
					copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
				}
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	/**
	 * 获取指定路径剩余空间
	 * @param path
	 * @return
	 */
	public static long getSDFreeSize(String path){
		//取得SD卡文件路径
		// File path = Environment.getExternalStorageDirectory();
		if(!new File(path).exists()){
			return 0;
		}
		StatFs sf = new StatFs(path);
		//获取单个数据块的大小(Byte)
		long blockSize = sf.getBlockSize();
		//空闲的数据块的数量
		long freeBlocks = sf.getAvailableBlocks();
		//返回SD卡空闲大小
		//return freeBlocks * blockSize;  //单位Byte
		//return (freeBlocks * blockSize)/1024;   //单位KB
		return (freeBlocks * blockSize)/1024 /1024; //单位MB
	}

	/**
	 * 获取指定路径总容量
	 * @param path
	 * @return
	 */
	public static long getSDAllSize(String path){
		//取得SD卡文件路径
		//File path = Environment.getExternalStorageDirectory();
		if(!new File(path).exists()){
			return 0;
		}
		StatFs sf = new StatFs(path);
		//获取单个数据块的大小(Byte)
		long blockSize = sf.getBlockSize();
		//获取所有数据块数
		long allBlocks = sf.getBlockCount();
		//返回SD卡大小
		//return allBlocks * blockSize; //单位Byte
		//return (allBlocks * blockSize)/1024; //单位KB
		return (allBlocks * blockSize)/1024/1024; //单位MB
	}
	/**
	 * 获取文件夹内容大小
	 * @param f
	 * @return
	 */
	public static long getFileListSize(File f) {
		long size = 0;
		if(f != null || f.exists()){
			File flist[] = f.listFiles();
			if(flist != null && flist.length != 0){
				for (int i = 0; i < flist.length; i++) {
					if (flist[i].isDirectory()) {
						size = size + getFileListSize(flist[i]);
					} else {
						size = size + flist[i].length();
					}
				}
			}
		}
		return size;
	}

	public static boolean fielExists(String path){
		File file = new File(path);
		if (file != null && file.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * 删除目录
	 * @param filepath
	 * @throws IOException
	 */
	public static Boolean del(File f){
		try {
			if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
				if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
					f.delete();
				} else {// 若有则把文件放进数组，并判断是否有下级目录
					File delFile[] = f.listFiles();
					int i = f.listFiles().length;
					for (int j = 0; j < i; j++) {
						if (delFile[j].isDirectory()) {
							File f1 = new File(delFile[j].getAbsolutePath());
							del(f1);// 递归调用del方法并取得子目录路径
						}
						delFile[j].delete();// 删除文件
					}
				}
			}
			f.delete();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	//读取一个文件夹下所有文件及子文件夹下的所有文件
	public  List<File> ReadAllFile(String filePath) {
		File f = null;
		f = new File(filePath);
		File[] files = f.listFiles(); // 得到f文件夹下面的所有文件。
		for (File file : files) {
			if (file.isDirectory()) {
				// 如何当前路劲是文件夹，则循环读取这个文件夹下的所有文件
				ReadAllFile(file.getAbsolutePath());
			} else {
				list.add(file);
			}
		}
		return list;
	}
	/**
	 * 根据传入的两个时间段，来匹配合适的file文件
	 * @param date1  yyyy-MM-dd HH:mm:ss
	 * @param date2  yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public  List<File> listBingoFile(String date1,String date2){
		List<File> fileList = new ArrayList<File>();
		//fileList = ReadAllFile(Constants.FILE_PATH+".dssApp/record/");
		fileList = ReadAllFile("D:\\test");
		List<File> bingoFileList = new ArrayList<File>();
		for(File file:fileList){
			long time =file.lastModified();
			Date date = new Date(time);
			if(DateUtil.isBetweenDate1AndDate2(date1, date2, date)){
				bingoFileList.add(file);
			}
		}
		return bingoFileList;
	}

	/**
	 * 文件转化为字节数组
	 */
	public static byte[] getBytesFromFile(File file) {
		if (file == null) {
			return null;
		}
		try {
			FileInputStream stream = new FileInputStream(file);
			byte[] b = new byte[stream.available()];
			stream.read(b);
			stream.close();
			return b;
		} catch (IOException e) {
		}
		return null;
	}

	/**
	 * 文件转化为字节数组
	 */
	public static byte[] getBytes(File file){
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	/**
	 * 文件转化为ArrayList<byte[]>
	 * 注意：每个包512个字节
	 */
	public static ArrayList<byte[]> file2ByteList(File file){
		byte[] buffer = getBytes(file);
		ArrayList<byte[]> list = null;
		if(buffer != null && buffer.length!=0){
			list = new ArrayList<byte[]>();
			int size = 0;
			int lastLength = 0;
			if(buffer.length%512 == 0){
				size = buffer.length/512;
				lastLength = 512;
			}else{
				size = buffer.length/512+1;
				lastLength = buffer.length%512;
			}
			for(int i = 0;i<size;i++){
				byte[] subData = null;
				if(i == (size-1)){
					// 最后一包
					subData = Tools.byteTobyte(buffer, 512*i, lastLength);
				}else{
					// 非最后一包
					subData = Tools.byteTobyte(buffer, 512*i, 512);
				}
				list.add(subData);
			}
		}
		return list;
	}

	/**
	 * 复制单个文件
	 * @param oldPath String 原文件路径
	 * @param newPath String 复制后路径
	 * @return boolean
	 */
	public static Boolean copyFileWithCreatePathForRecording(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			//检查文件路径是否存在
			File filePath = new File(newPath);
			filePath.deleteOnExit();
			if (oldfile.exists()) { //文件存在时
				InputStream inStream = new FileInputStream(oldPath); //读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				int length;
				while ( (byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; //字节数 文件大小
					System.out.println(bytesum);
					fs.write(buffer, 0, byteread);
				}
				fs.flush();
				fs.close();
				inStream.close();
				return true;
			}
			return false;
		}
		catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e), e);
			e.printStackTrace();
			return false;

		}

	}
}
